from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from sqlalchemy import select
from models.user import User, Role, Power
from typing import Dict, List

###########
## 数据库层
###########
__all__ = ["Repository"]


class Repository:
    def __init__(self, session: AsyncSession):
        self.session = session
    
    async def has_perm(self, user_id: int, power_name: str) -> bool:
        # 查询是否存在指定权限
        query_power = select(Power).where(Power.name == power_name)
        res_power = await self.session.execute(query_power)
        power = res_power.scalar()
        
        if power is None:
            return False

        # 查询用户及其角色和权限
        query_user = (
            select(User)
            .where(User.id == user_id)
            .options(selectinload(User.roles).selectinload(Role.powers))
        )
        res_user = await self.session.execute(query_user)
        user = res_user.scalar()

        if user is None:
            return False

        # 构建用户权限列表
        user_perm = [power.id for role in user.roles for power in role.powers]
        
        # 更新用户权限字典
        user_perm_list[user_id] = user_perm
        
        return power.id in user_perm

user_perm_list: Dict[int, List[int]] = {}                